package auth

import (
	"crypto/md5"
	"fmt"
	"io"
	"strconv"
	"strings"
	"time"
)

// ValidateSignature validates the request signature
func ValidateSignature(method, path string, timestamp int64, body, appSecret, signature string) bool {
	expected := GenerateSignature(method, path, timestamp, body, appSecret)
	return expected == signature
}

// GenerateSignature generates MD5 signature for a request
func GenerateSignature(method, path string, timestamp int64, body, appSecret string) string {
	// Build the plaintext: METHOD + PATH + TIMESTAMP + BODY + APP_SECRET
	plaintext := strings.ToUpper(method) + path + strconv.FormatInt(timestamp, 10) + body + appSecret

	// Calculate MD5
	h := md5.New()
	io.WriteString(h, plaintext)
	return fmt.Sprintf("%x", h.Sum(nil))
}

// GetCurrentTimestamp returns current timestamp in milliseconds
func GetCurrentTimestamp() int64 {
	return time.Now().UnixMilli()
}

// IsTimestampValid checks if timestamp is within acceptable range (e.g., 5 minutes)
func IsTimestampValid(timestamp int64, maxAgeSeconds int64) bool {
	now := GetCurrentTimestamp()
	diff := now - timestamp
	if diff < 0 {
		diff = -diff
	}
	return diff <= (maxAgeSeconds * 1000)
}
